﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using GalaSoft.MvvmLight.Messaging;

namespace TestApp.Messages
{
    public class MessageReceiver<T> where T : InitMessageBase
    {
        private Action<T> _handler = null;
        private T _message = null;


        public MessageReceiver(Action<T> handler)
        {
            this._handler = handler;


            // Wait for messages
            Messenger.Default.Register<T>(this, message =>
            {
                if (this._message != null && this._message != message && !message.Received)
                {
                    message.Received = true;


                    this.OnMessageReceived(message);
                }
            });
        }


        /// <summary>
        /// Send empty message on instantiation
        /// </summary>
        /// <param name="message"></param>
        public MessageReceiver(Action<T> handler, bool sendInitMessage)
            : this(handler)
        {
            if (sendInitMessage)
            {
                this._message = Activator.CreateInstance(typeof(T)) as T;


                // Send empty message
                Messenger.Default.Send<T>(this._message);
            }
        }


        private void OnMessageReceived(T message)
        {
            if (this._handler != null)
                this._handler(message);
        }
    }
}
